package com.example.fx.search

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.HistoryEntity
import com.example.base.mvvm.BaseActivity
import com.example.fx.R
import com.example.fx.adapter.GoodsSearchAdapter
import com.example.fx.databinding.ActivitySearchBinding
import com.example.fx.db.AppDbUtils
import okhttp3.internal.notify

@Route(path = "/app/SearchActivity")
class SearchActivity : BaseActivity<SearchViewModel,ActivitySearchBinding>() {
    lateinit var goodsSearchAdapter: GoodsSearchAdapter
    val historyList = mutableListOf<HistoryEntity>()

    override fun getLayout(): Int  = R.layout.activity_search

    override fun getViewModel(): Class<SearchViewModel>  = SearchViewModel::class.java

    @SuppressLint("MissingInflatedId")
    override fun initView() {
        goodsSearchAdapter = GoodsSearchAdapter()
        binding.rvGoods.adapter = goodsSearchAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(this,2)
        //点击执行搜索
        binding.sv.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                if(query!=null){
                    viewModel.search(query,1,10)
                    //保存搜索关键词
                    AppDbUtils.getDb().getHistoryDao().insert(HistoryEntity(query))
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return false
            }
        })
        //显示历史搜索记录
        historyList.addAll(AppDbUtils.getDb().getHistoryDao().query())
        if(historyList.size>0){
            //有数据
            binding.cg.removeAllViews()//清空之前的数据
            //依次添加
            historyList.forEach {
                var keyword = it.keyword
                val itemChip = LayoutInflater.from(this).inflate(R.layout.item_chip,null)
                itemChip.findViewById<TextView>(R.id.name).text = keyword
                binding.cg.addView(itemChip)

                itemChip.setOnClickListener {
                    binding.sv.setQuery(keyword,true)
                }
            }
        }
    }

    override fun initData() {
        //观察搜索结果
        viewModel.searchSuccess.observe(this){
            if(it.code==200){
                goodsSearchAdapter.data.clear()
                goodsSearchAdapter.data.addAll(it.data.list)
                goodsSearchAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.searchFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

}